package com.xxx.demo.controller;

import cn.hutool.captcha.LineCaptcha;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xxx.demo.entity.TUsers;
import com.xxx.demo.service.impl.UserServiceImpl;
import com.xxx.demo.tiaoJian.UserTiaoJian;
import com.xxx.demo.vo.UserPageVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/manage")
public class UserController {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private UserServiceImpl userService;
    /**
     * 用户登录，判断用户是否存在
     * @param userName
     * @param password
     * @param veryCode
     * @param session
     * @param model
     * @return
     */
    @RequestMapping("/login.do")
    public String login(String userName, String password, String veryCode, HttpSession session, Model model, HttpServletRequest req){
        LineCaptcha lineCaptcha= (LineCaptcha) session.getAttribute("lineCaptcha");
        boolean feiFa=lineCaptcha.verify(veryCode);
       if (!feiFa){ //验证码不正确
            model.addAttribute("msg2","验证码错误");
            return "manage/login2";
        }

        TUsers users=userService.selectAdmin(userName,password);
        if(users!=null){
            //使用session
            session.setAttribute("user",users);
            req.setAttribute("user",users);
            return "redirect:/manage/selectAdminPage";//重定向
//            return "redirect:/manage/user";
        }else {
            model.addAttribute("msg","用户名或者密码错误，请重新输入");
            return "manage/login2";
        }
    }

    /**
     * 添加用户
     * @param users
     * @return
     */
    @RequestMapping("/addUser")
    @ResponseBody
    //@ModelAttribute 用实体类接受请求，保证请求参数名与实体类属性名一致
    public String addUser(@ModelAttribute TUsers users){
        userService.saveUser(users);
        return "1";
    }
    //
    ///**
    // * 查找所有用户，并显示
    // * @param model
    // * @return
    // */
    //@RequestMapping("/user")
    //public String findUsers(Model model, @ModelAttribute("tj") UserTiaoJian userTiaoJian){
    //    if (userTiaoJian.getPageNo()==null){
    //        userTiaoJian.setPageNo(1);
    //    }
    //    if (userTiaoJian.getPageSize()==null){
    //        userTiaoJian.setPageSize(3);
    //    }
    //
    //  userTiaoJian.setTotal(userService.queryCountUser(userTiaoJian));
    //  if (userTiaoJian.getTotal()!=0&&userTiaoJian.getTotal()!=null){
    //      userTiaoJian.setTotalPages((int) Math.ceil(userTiaoJian.getTotal().doubleValue()/userTiaoJian.getPageSize().doubleValue()));
    //  }
    //   List<TUsers> users= userService.queryUserByTiaoJian(userTiaoJian);
    //   model.addAttribute("users",users);
    //    return "manage/user";
    //}
    //
    /**
     * 根据用户id查找用户
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/queryUserById")
    public String findUserById(Long id, Model model,HttpSession session){
        TUsers users =userService.queryUserById(id);
        model.addAttribute("users",users);
        TUsers admin1= (TUsers) session.getAttribute("user");
        model.addAttribute("adminSession",admin1);
        return "manage/updateUser";
    }

    /**
     * 修改用户
     * @param users
     * @return
     */
    @RequestMapping("/updateUser")
    @ResponseBody
    public String updateUser(@ModelAttribute TUsers users){
        userService.updateUser(users);
        //return "redirect:/manage/user";
        return "1";
    }



    /**
     * 使用RestFul查找用户
     */
    @ResponseBody
    @GetMapping("/user/{userId}")//get请求
    public String userInfo(@PathVariable Integer userId){
        System.out.println("get请求 用户id： "+userId);
        return null;
    }
    /**
     * 使用RestFul删除用户
     */
    @ResponseBody
    @DeleteMapping("/user/{userId}")
    public String deleteUser(@PathVariable Integer userId){
        System.out.println("delete请求 用户id："+userId);
        return null;
    }

    /**
     * 以下代码是改造代码
     *
     */

    /**
     * 分页查询所有管理员
     * @param admin
     * @param pageNo
     * @param pageSize
     * @param model
     * @return
     */
    @RequestMapping("/selectAdminPage")
    public String selectAdminPage(@ModelAttribute("admin") TUsers admin, Integer pageNo, Integer pageSize, Model model, HttpSession session){
        if (pageNo==null || pageNo<1){
            pageNo=1;
        }
        if (pageSize==null || pageSize<1){
            pageSize=3;
        }
        IPage<TUsers> adminIPage=userService.selectAdminPage(pageNo,pageSize,admin);
        IPage<UserPageVo> userPageVoIPage = new Page<>();
        List<TUsers> users = adminIPage.getRecords();
        List<UserPageVo> userPageVos = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(users)){
            for (TUsers data:users){
                UserPageVo userPageVo = new UserPageVo();
                BeanUtil.copyProperties(data,userPageVo);
                userPageVo.setIdStr(data.getId() + "!");
                userPageVos.add(userPageVo);
            }
        }
        BeanUtil.copyProperties(adminIPage,userPageVoIPage);
        userPageVoIPage.setRecords(userPageVos);
        LOGGER.info("分页查询出参：{}" + userPageVoIPage.getRecords().toString());
        TUsers admin1= (TUsers) session.getAttribute("user");
        model.addAttribute("adminSession",admin1);
        model.addAttribute("adminIPage",userPageVoIPage);
        return "manage/user";
    }

    /**
     * 根据用户id删除（假）用户
     * @param id
     * @return
     */
    @RequestMapping("/deleteUserById")
    @ResponseBody
    public String deleteUserById(String id) throws Exception {
        id = id.replace("!","");
        System.out.println(id);
        Long aLong = Long.valueOf(id);
        userService.deleteUserById(aLong);
        return "1";
    }
}
